<template>
    <view class="add-seed-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header
            :title="isEdit ? '编辑播种管理' : '播种管理'"
        ></page-header>

        <view class="land-selection">
            <view class="section-title">选择地块</view>
            <view class="all-select">
                <checkbox
                    :checked="allLandSelected"
                    @click="toggleAllLand"
                ></checkbox>
                <text>全选</text>
            </view>

            <view class="land-grid">
                <view
                    class="land-item"
                    v-for="(land, index) in landList"
                    :key="index"
                    :class="{ active: land.selected }"
                    @click="selectLand(index)"
                >
                    <image :src="land.image" mode="aspectFill"></image>
                    <text>{{ land.name }}</text>
                </view>
            </view>
        </view>

        <view class="section-selection">
            <view class="section-title">选择条田</view>
            <view class="all-select">
                <checkbox
                    :checked="allSectionsSelected"
                    color="#4062F6"
                    @click="toggleAllSections"
                ></checkbox>
                <text>全选</text>
            </view>

            <view class="section-grid">
                <view
                    class="section-item"
                    v-for="(section, index) in sectionList"
                    :key="index"
                    :class="{ active: section.selected }"
                    @click="selectSection(index)"
                >
                    <text>{{ section.name }}</text>
                </view>
            </view>
        </view>

        <view class="basic-info">
            <view class="section-title">基础信息</view>

            <uni-forms
                ref="form"
                :modelValue="formData"
                :rules="rules"
                validateTrigger="bind"
                label-position="top"
            >
                <uni-forms-item label="播种时间" name="dateRange" required>
                    <uni-datetime-picker
                        type="daterange"
                        v-model="formData.dateRange"
                        :border="false"
                        :label-width="200"
                        @change="dateRangeChange"
                    >
                        <view class="uni-date-picker-container">
                            <text
                                :class="{
                                    placeholder: !formData.dateRangeText,
                                }"
                                >{{
                                    formData.dateRangeText || "请选择播种时间"
                                }}</text
                            >
                            <view class="date-icon">
                                <roc-icon-plus
                                    type="fas"
                                    name="calendar-alt"
                                    :size="18"
                                    color="#999"
                                ></roc-icon-plus>
                            </view>
                        </view>
                    </uni-datetime-picker>
                </uni-forms-item>

                <uni-forms-item label="农作物类型" name="seedType" :label-width="200" required>
                    <uni-data-select
                        v-model="formData.seedType"
                        :localdata="seedTypesData"
                        placeholder="请选择农作物类型"
                        @change="handleSeedTypeChange"
                    ></uni-data-select>
                </uni-forms-item>

                <uni-forms-item label="种子名称" name="seedName" required>
                    <uni-data-select
                        v-model="formData.seedName"
                        :localdata="currentSeedNamesData"
                        placeholder="请选择种子名称"
                    ></uni-data-select>
                </uni-forms-item>

                <uni-forms-item label="播种面积" name="amount" required>
                    <uni-easyinput
                        type="digit"
                        v-model="formData.amount"
                        placeholder="请输入"
                        suffixIcon="单位"
                        suffixIconStyle="color: #999;font-size: 28rpx;"
                        suffix-text="亩"
                    ></uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="负责人" name="manager" required>
                    <uni-easyinput
                        v-model="formData.manager"
                        placeholder="请输入负责人姓名"
                    ></uni-easyinput>
                </uni-forms-item>

                <uni-forms-item label="播种方式" name="seedMethod" required>
                    <view class="form-two-columns">
                        <uni-data-select
                            v-model="formData.seedMethod"
                            :localdata="seedMethodsData"
                            placeholder="请选择播种方式"
                            class="half"
                        ></uni-data-select>

                        <uni-data-select
                            v-model="formData.seedMachine"
                            :localdata="seedMachinesData"
                            placeholder="选择播种机械"
                            class="half"
                        ></uni-data-select>
                    </view>
                </uni-forms-item>
            </uni-forms>
        </view>

        <view class="photo-section">
            <view class="section-title">现场照片</view>

            <view class="photo-upload-area">
                <view class="upload-btn" @click="uploadImage">
                    <roc-icon-plus
                        type="fas"
                        name="camera"
                        :size="24"
                        color="#2E6B34"
                    ></roc-icon-plus>
                </view>

                <view
                    class="photo-preview"
                    v-for="(img, index) in formData.images"
                    :key="index"
                >
                    <image :src="img" mode="aspectFill"></image>
                    <view class="delete-photo" @click.stop="removeImage(index)">
                        <roc-icon-plus
                            type="fas"
                            name="times"
                            :size="18"
                            color="#fff"
                        ></roc-icon-plus>
                    </view>
                </view>
            </view>
        </view>

        <button class="submit-btn" @click="submitForm">点击上传</button>
    </view>
</template>

<script>
import PageHeader from "@/components/PageHeader/index.vue";

export default {
    components: {
        PageHeader,
    },
    data() {
        return {
            isEdit: false,
            editId: null,
            formData: {
                seedType: "",
                seedName: "",
                amount: "",
                dateRange: [],
                dateRangeText: "",
                manager: "",
                seedMethod: "",
                seedMachine: "",
                images: [],
            },
            rules: {
                dateRange: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请选择播种时间",
                        },
                    ],
                },
                seedType: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请选择农作物类型",
                        },
                    ],
                },
                seedName: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请选择种子名称",
                        },
                    ],
                },
                amount: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请输入播种面积",
                        },
                        {
                            format: "number",
                            errorMessage: "请输入有效的数字",
                        },
                    ],
                },
                manager: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请输入负责人",
                        },
                    ],
                },
                seedMethod: {
                    rules: [
                        {
                            required: true,
                            errorMessage: "请选择播种方式",
                        },
                    ],
                },
            },
            landList: [
                {
                    name: "一号地块",
                    image: "/static/agriculture/land/land1.jpg",
                    selected: false,
                },
                {
                    name: "二号地块",
                    image: "/static/agriculture/land/land1.jpg",
                    selected: false,
                },
                {
                    name: "三号地块",
                    image: "/static/agriculture/land/land1.jpg",
                    selected: false,
                },
                {
                    name: "四号地块",
                    image: "/static/agriculture/land/land1.jpg",
                    selected: false,
                },
                {
                    name: "五号地块",
                    image: "/static/agriculture/land/land1.jpg",
                    selected: false,
                },
                {
                    name: "六号地块",
                    image: "/static/agriculture/land/land1.jpg",
                    selected: true,
                },
                {
                    name: "七号地块",
                    image: "/static/agriculture/land/land1.jpg",
                    selected: false,
                },
                {
                    name: "八号地块",
                    image: "/static/agriculture/land/land1.jpg",
                    selected: false,
                },
            ],
            sectionList: [
                { name: "1号", selected: false },
                { name: "2号", selected: false },
                { name: "3号", selected: false },
                { name: "4号", selected: false },
                { name: "5号", selected: false },
                { name: "6号", selected: false },
                { name: "7号", selected: false },
                { name: "8号", selected: false },
                { name: "9号", selected: false },
                { name: "10号", selected: false },
                { name: "11号", selected: false },
                { name: "12号", selected: false },
                { name: "13号", selected: false },
                { name: "14号", selected: false },
                { name: "15号", selected: false },
            ],
            seedTypes: ["水稻", "小麦", "玉米", "大豆"],
            seedTypesData: [
                { value: "水稻", text: "水稻" },
                { value: "小麦", text: "小麦" },
                { value: "玉米", text: "玉米" },
                { value: "大豆", text: "大豆" },
            ],
            seedNames: {
                水稻: ["花稻14", "超级稻3号", "中早39", "粳稻102"],
                小麦: ["冬麦8号", "中麦175", "郑麦366"],
                玉米: ["金玉1号", "郑单958", "先玉335"],
                大豆: ["中黄13", "黄泡1号", "绥农14"],
            },
            currentSeedNamesData: [],
            seedMethodsData: [
                { value: "无人机", text: "无人机" },
                { value: "机械", text: "机械" },
                { value: "人工", text: "人工" },
            ],
            seedMachinesData: [
                { value: "播种机A", text: "播种机A" },
                { value: "播种机B", text: "播种机B" },
                { value: "播种机C", text: "播种机C" },
            ],
        };
    },
    computed: {
        allLandSelected() {
            return this.landList.every((land) => land.selected);
        },
        allSectionsSelected() {
            return this.sectionList.every((section) => section.selected);
        },
    },
    onLoad(options) {
        if (options.id) {
            this.isEdit = true;
            this.editId = parseInt(options.id);
            this.loadSeedData(this.editId);
        }
    },
    methods: {
        loadSeedData(id) {
            // 在实际应用中，这里应该从API获取数据
            // 这里模拟加载编辑数据
            const seedData = this.getMockSeedData(id);
            if (seedData) {
                // 设置日期范围
                const startDate = new Date(seedData.date);
                const endDate = new Date(seedData.date);
                endDate.setDate(endDate.getDate() + 1);

                this.formData = {
                    seedType: seedData.type,
                    seedName: seedData.name,
                    amount: seedData.amount.toString(),
                    dateRange: [
                        startDate.toISOString().split("T")[0],
                        endDate.toISOString().split("T")[0],
                    ],
                    dateRangeText: `${this.formatDate(
                        startDate
                    )} 至 ${this.formatDate(endDate)}`,
                    manager: seedData.person,
                    seedMethod: seedData.method || "无人机",
                    seedMachine: "",
                    images: seedData.images || [],
                };

                // 初始化种子名称下拉数据
                this.handleSeedTypeChange();
            }
        },
        getMockSeedData(id) {
            const mockData = [
                {
                    id: 1,
                    type: "水稻",
                    name: "花稻14",
                    cropType: "水稻-花稻14",
                    field: "1号地块",
                    amount: 45.3,
                    method: "无人机",
                    date: "2023-11-15 09:30",
                    person: "张明远",
                    images: ["/static/agriculture/seed/rice1.jpg"],
                },
                {
                    id: 2,
                    type: "水稻",
                    name: "超级稻3号",
                    amount: 38.7,
                    method: "人工",
                    date: "2023-11-14 14:15",
                    person: "李思雨",
                    images: [],
                },
                {
                    id: 3,
                    type: "小麦",
                    name: "冬麦8号",
                    amount: 32.3,
                    method: "机械",
                    date: "2023-11-13 10:45",
                    person: "王建国",
                    images: [],
                },
            ];
            return mockData.find((item) => item.id === id);
        },
        formatDate(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, "0");
            const day = date.getDate().toString().padStart(2, "0");
            return `${year}-${month}-${day}`;
        },
        dateRangeChange(e) {
            if (e && e.length === 2) {
                const startDate = new Date(e[0]);
                const endDate = new Date(e[1]);
                this.formData.dateRangeText = `${this.formatDate(
                    startDate
                )} 至 ${this.formatDate(endDate)}`;
            } else {
                this.formData.dateRangeText = "";
            }
        },
        handleSeedTypeChange() {
            // 根据选择的农作物类型，更新种子名称下拉选项
            if (this.formData.seedType) {
                const names = this.seedNames[this.formData.seedType] || [];
                this.currentSeedNamesData = names.map((name) => ({
                    value: name,
                    text: name,
                }));
            } else {
                this.currentSeedNamesData = [];
            }
            // 重置种子名称
            if (
                this.formData.seedName &&
                !this.currentSeedNamesData.some(
                    (item) => item.value === this.formData.seedName
                )
            ) {
                this.formData.seedName = "";
            }
        },
        selectLand(index) {
            this.landList[index].selected = !this.landList[index].selected;
        },
        selectSection(index) {
            this.sectionList[index].selected =
                !this.sectionList[index].selected;
        },
        toggleAllLand() {
            const newValue = !this.allLandSelected;
            this.landList.forEach((land) => (land.selected = newValue));
        },
        toggleAllSections() {
            const newValue = !this.allSectionsSelected;
            this.sectionList.forEach(
                (section) => (section.selected = newValue)
            );
        },
        uploadImage() {
            uni.chooseImage({
                count: 1,
                success: (res) => {
                    this.formData.images.push(res.tempFilePaths[0]);
                },
            });
        },
        removeImage(index) {
            this.formData.images.splice(index, 1);
        },
        validateForm() {
            // 检查是否选择了地块
            if (!this.landList.some((land) => land.selected)) {
                uni.showToast({
                    title: "请选择至少一个地块",
                    icon: "none",
                });
                return false;
            }

            // 检查是否选择了条田
            if (!this.sectionList.some((section) => section.selected)) {
                uni.showToast({
                    title: "请选择至少一个条田",
                    icon: "none",
                });
                return false;
            }

            return true;
        },
        submitForm() {
            // 使用uni-forms的验证方法
            this.$refs.form
                .validate()
                .then((result) => {
                    if (result.valid && this.validateForm()) {
                        this.submitFormData();
                    }
                })
                .catch((errors) => {
                    console.log("表单错误信息：", errors);
                });
        },
        submitFormData() {
            // 构建提交的数据对象
            const submitData = {
                id: this.isEdit ? this.editId : new Date().getTime(),
                type: this.formData.seedType,
                name: this.formData.seedName,
                amount: parseFloat(this.formData.amount),
                date: this.formData.dateRangeText.split("至")[0].trim(),
                person: this.formData.manager,
                method: this.formData.seedMethod,
                machine: this.formData.seedMachine,
                images: this.formData.images,
                lands: this.landList
                    .filter((land) => land.selected)
                    .map((land) => land.name),
                sections: this.sectionList
                    .filter((section) => section.selected)
                    .map((section) => section.name),
            };

            // 在实际应用中，这里应该调用API提交数据
            // 这里简化处理，显示成功提示并返回
            uni.showLoading({
                title: "提交中...",
            });

            setTimeout(() => {
                uni.hideLoading();
                uni.showToast({
                    title: this.isEdit ? "修改成功" : "添加成功",
                    icon: "success",
                    duration: 2000,
                    success: () => {
                        setTimeout(() => {
                            // 返回上一页并刷新
                            uni.navigateBack();
                        }, 1500);
                    },
                });
            }, 1000);
        },
    },
};
</script>

<style lang="scss">
.add-seed-container {
    min-height: 100vh;
    background-color: #f5f5f5;

    .land-selection {
        margin-top: 120rpx; /* 为固定定位的页头留出空间 */
        background-color: #fff;
        padding: 30rpx;
        margin-bottom: 20rpx;

        .land-grid {
            display: flex;
            flex-wrap: wrap;
            margin: 0 -10rpx;

            .land-item {
                width: calc(25% - 20rpx);
                margin: 10rpx;
                position: relative;
                overflow: hidden;
                border-radius: 8rpx;
                height: 160rpx;

                image {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }

                text {
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    background-color: rgba(0, 0, 0, 0.5);
                    color: #fff;
                    font-size: 24rpx;
                    text-align: center;
                    padding: 8rpx 0;
                }

                &.active {
                    border: 3rpx solid #4062f6;

                    &::after {
                        content: "";
                        position: absolute;
                        top: 0;
                        left: 0;
                        right: 0;
                        bottom: 0;
                        background-color: rgba(64, 98, 246, 0.2);
                    }
                }
            }
        }
    }

    .section-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 20rpx;
    }

    .all-select {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        checkbox {
            margin-right: 10rpx;
            transform: scale(0.8);
        }

        text {
            font-size: 26rpx;
            color: #666;
        }
    }

    .section-selection {
        background-color: #fff;
        padding: 30rpx;
        margin-bottom: 20rpx;

        .section-grid {
            display: flex;
            flex-wrap: wrap;
            margin: 0 -10rpx;

            .section-item {
                width: calc(20% - 20rpx);
                margin: 10rpx;
                height: 80rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                background-color: #f5f5f5;
                border-radius: 8rpx;

                text {
                    font-size: 26rpx;
                    color: #333;
                }

                &.active {
                    background-color: #4062f6;

                    text {
                        color: #fff;
                    }
                }
            }
        }
    }

    .basic-info {
        background-color: #fff;
        padding: 30rpx;
        margin-bottom: 20rpx;

        .uni-date-picker-container {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10rpx 20rpx;
            border: solid 1px #e5e5e5;
            // 盒子模型
            box-sizing: border-box;
            .date-icon {
                height: 100%;
                display: flex;
                align-items: center;
            }

            .placeholder {
                color: #999;
            }
        }

        .form-two-columns {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 20rpx;

            .half {
                width: calc(50% - 10rpx);
            }
        }
    }

    .photo-section {
        background-color: #fff;
        padding: 30rpx;
        margin-bottom: 20rpx;

        .photo-upload-area {
            display: flex;
            flex-wrap: wrap;

            .upload-btn {
                width: 160rpx;
                height: 160rpx;
                display: flex;
                align-items: center;
                justify-content: center;
                border: 1rpx dashed #2e6b34;
                border-radius: 8rpx;
                margin-right: 20rpx;
                margin-bottom: 20rpx;
            }

            .photo-preview {
                width: 160rpx;
                height: 160rpx;
                position: relative;
                margin-right: 20rpx;
                margin-bottom: 20rpx;
                border-radius: 8rpx;
                overflow: hidden;

                image {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }

                .delete-photo {
                    position: absolute;
                    top: 8rpx;
                    right: 8rpx;
                    width: 36rpx;
                    height: 36rpx;
                    background-color: #ff5252;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
            }
        }
    }

    .submit-btn {
        width: 100%;
        height: 100rpx;
        background-color: #2e6b34;
        color: #fff;
        font-size: 32rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 0;
        margin-top: 40rpx;
    }
}

// 覆盖uni-forms的部分默认样式
:deep(.uni-forms-item) {
    margin-bottom: 22rpx;
}

:deep(.uni-forms-item__label) {
    font-size: 28rpx;
    color: #333;
    padding-bottom: 8rpx;
}

:deep(.uni-easyinput) {
    background-color: #f5f5f5 !important;
    border-radius: 8rpx !important;
}

:deep(.uni-data-select) {
    background-color: #f5f5f5 !important;
    border-radius: 8rpx !important;
}

:deep(.uni-select--border) {
    border: none !important;
}

:deep(.uni-forms-item__content) {
    width: 100%;
}
</style>
